#!/usr/bin/env python3
"""
MySQL数据验证脚本

验证从SQLite迁移到MySQL后的数据完整性

Author: zhaozeliang
Date: 2025-01-14
"""

import os
import sys

# 设置Django环境
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'wealth_backend.settings_mysql')

try:
    import django  # type: ignore
    django.setup()
except ImportError as e:
    print(f"Django导入错误: {e}")
    print("请确保已安装Django并且在正确的虚拟环境中运行")
    sys.exit(1)

def verify_data():
    """验证数据完整性"""
    try:
        # 导入模型
        from users.models import User
        from portfolios.models import Portfolio
        from products.models import Product
        from data_service.models import FundInfo, FundInfoDetail, FundNavDetail
        
        print("MySQL数据库连接验证")
        print("=" * 50)
        
        # 检查各个模型的数据
        models_data = [
            ('用户 (User)', User),
            ('投资组合 (Portfolio)', Portfolio),
            ('产品 (Product)', Product),
            ('基金信息 (FundInfo)', FundInfo),
            ('基金详情 (FundInfoDetail)', FundInfoDetail),
            ('基金净值 (FundNavDetail)', FundNavDetail),
        ]
        
        total_records = 0
        
        for name, model in models_data:
            try:
                count = model.objects.count()
                total_records += count
                print(f"{name:<30} {count:>10} 条记录")
                
                # 显示最新的几条记录
                if count > 0:
                    latest = model.objects.first()
                    print(f"  最新记录ID: {latest.id if hasattr(latest, 'id') else 'N/A'}")
                    
            except Exception as e:
                print(f"{name:<30} {'错误':>10} - {e}")
        
        print("-" * 50)
        print(f"总记录数: {total_records}")
        
        # 测试基金数据查询
        print("\n基金数据查询测试")
        print("-" * 30)
        
        if FundInfo.objects.exists():
            fund = FundInfo.objects.first()
            print(f"基金代码: {fund.fund_code}")
            print(f"基金名称: {fund.fund_name}")
            
            # 查询该基金的净值数据
            nav_count = FundNavDetail.objects.filter(fund_code=fund.fund_code).count()
            print(f"净值记录数: {nav_count}")
        else:
            print("暂无基金信息数据")
        
        # 测试用户数据
        print("\n用户数据测试")
        print("-" * 20)
        
        if User.objects.exists():
            user = User.objects.first()
            print(f"用户名: {user.username}")
            print(f"邮箱: {user.email}")
            print(f"创建时间: {user.date_joined}")
        else:
            print("暂无用户数据")
        
        print("\n=" * 50)
        print("MySQL数据验证完成！")
        print("数据库迁移成功，所有数据已正确导入MySQL")
        
        return True
        
    except Exception as e:
        print(f"验证过程中出现错误: {e}")
        return False

def test_database_connection():
    """测试数据库连接"""
    try:
        try:
            from django.db import connection  # type: ignore
        except ImportError as e:
            print(f"Django数据库模块导入错误: {e}")
            sys.exit(1)
        
        with connection.cursor() as cursor:
            cursor.execute("SELECT VERSION()")
            version = cursor.fetchone()[0]
            print(f"MySQL版本: {version}")
            
            cursor.execute("SELECT DATABASE()")
            database = cursor.fetchone()[0]
            print(f"当前数据库: {database}")
            
            cursor.execute("SHOW TABLES")
            tables = cursor.fetchall()
            print(f"数据表数量: {len(tables)}")
            
        return True
        
    except Exception as e:
        print(f"数据库连接测试失败: {e}")
        return False

def main():
    """主函数"""
    print("开始MySQL数据验证...")
    print("=" * 60)
    
    # 1. 测试数据库连接
    print("1. 数据库连接测试")
    if not test_database_connection():
        print("数据库连接失败，验证终止")
        sys.exit(1)
    
    print("\n2. 数据完整性验证")
    # 2. 验证数据
    if not verify_data():
        print("数据验证失败")
        sys.exit(1)
    
    print("\n" + "=" * 60)
    print("所有验证通过！MySQL数据库迁移成功！")
    print("\n下一步：")
    print("1. 可以停止SQLite版本的服务器")
    print("2. 使用MySQL配置启动生产服务器")
    print("3. 更新前端配置连接到MySQL后端")

if __name__ == '__main__':
    main()